package tema10.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import tema10.persistence.ContactoDAO;
import tema10.persistence.ContactoPersistFactory;

//@WebListener No lo empleamos este Servlet
public class StartUpListener implements ServletContextListener {

    //private ContactoDAO contactoDAO;

    @Override
    public void contextInitialized(ServletContextEvent evt) {
        /*String url, driver, user, password, persistenceMechanism;
        ServletContext context = evt.getServletContext();
        String connectionFileName = context.getInitParameter("connectionConfigFile");
        InputStream is = context.getResourceAsStream(connectionFileName);
        Properties connectionFile = new Properties();
        try {
            connectionFile.load(is);
        } catch (IOException ex) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.SEVERE,
                    "Error cargando los parametros del fichero de configuracion de BD", ex);
            //En este caso sacamos los parametros del contexto
            url = context.getInitParameter("databaseURL");
            driver = context.getInitParameter("databaseDriver");
            user = context.getInitParameter("databaseUser");
            password = context.getInitParameter("databasePassword");
        }
        url = connectionFile.getProperty("url");
        driver = connectionFile.getProperty("driver");
        user = connectionFile.getProperty("user");
        password = connectionFile.getProperty("password");
        persistenceMechanism = context.getInitParameter("persistenceMechanism");
        
        Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Estableciendo conexion con la BD empleando: {0}...", persistenceMechanism);
        contactoDAO = ContactoPersistFactory.getContactoDAO(persistenceMechanism);
        boolean connected = contactoDAO.setUp(url, driver, user, password);
        if (!connected) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Error conectando a la BD");
            context.setAttribute("persistenceMechanism", "none");
        } else {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Conexion con la BD realizada con exito");
        }*/
    }

    @Override
    public void contextDestroyed(ServletContextEvent evt) {
        /*boolean disconnected = contactoDAO.disconnect();
        if (!disconnected) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.SEVERE,
                    "No se encontro el driver para la base de datos");
        }*/
    }
}